package com.feilo.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.feilo.job.GpsHisttoryDataJob;
import com.feilo.job.DistanceJob;

public class InitServlet extends HttpServlet {

	private static final long serialVersionUID = -1500219664549181418L;

	public void destroy() {
		super.destroy(); 
	}

	public void init() throws ServletException {
		System.out.println("init is working...");
		initGpsHistoryData();
		calDistance();
		
	}
	
	private void initGpsHistoryData() {
		System.out.println("开始初始化设备历史轨迹数据，每1个小时更新一次，从本小时59分59秒开始");
		SchedulerFactory schedulerfactory = new StdSchedulerFactory();
		Scheduler schedulerHistory = null;
		try {
			schedulerHistory = schedulerfactory.getScheduler();		
			JobDetail job = JobBuilder.newJob(GpsHisttoryDataJob.class).withIdentity("job1", "jgroup1").build();
			Trigger trigger = TriggerBuilder
					.newTrigger()
					.withIdentity("simpleTrigger1", "triggerGroup1")
					.withSchedule(CronScheduleBuilder.cronSchedule("59 59/60 * * * ?"))
					.startNow().build();
			schedulerHistory.scheduleJob(job, trigger);
			schedulerHistory.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void calDistance() {
		System.out.println("开始计算里程数，每天23时59分50秒开始计算");
		SchedulerFactory schedulerfactory = new StdSchedulerFactory();
		Scheduler schedulerDistance = null;
		try {
			schedulerDistance = schedulerfactory.getScheduler();	 
			JobDetail job2 = JobBuilder.newJob(DistanceJob.class).withIdentity("job2", "jgroup2").build();
			Trigger trigger2 = TriggerBuilder
					.newTrigger()
					.withIdentity("simpleTrigger2", "triggerGroup2")
					.withSchedule(CronScheduleBuilder.cronSchedule("50 59 23 * * ?"))
					.startNow().build();
			schedulerDistance.scheduleJob(job2, trigger2);
			schedulerDistance.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
